import COS from "cos-wx-sdk-v5";
import dayjs from "dayjs";

import { randomString } from "./index.js";

import { systemApi } from "@/api"; // 向后端请求腾讯云的参数
import { ENV } from "./index.js";

const SystemApi = systemApi();

const upload = (path, FilePath) => {
  return new Promise((resolve, reject) => {
    SystemApi.tencentCosTmp()
      .then((res) => {
        const fileExtension = FilePath.substring(FilePath.lastIndexOf(".") + 1);
        const Key = `/${path}/${dayjs().year()}/${dayjs().month()}/${dayjs().date()}/${randomString(
          32
        ).toLowerCase()}.${fileExtension}`;
        uni.showLoading({
          title: "上传中...",
          mask: true,
        });
        console.log("获取腾讯云COS临时秘钥", res);
        let info = res.data.info;
        const cos = new COS({
          SecretId: ENV.secretId,
          SecretKey: ENV.secretKey,
        });
        cos.postObject(
          {
            Bucket: info.Bucket /* 必须 */,
            Region: info.Region /* 存储桶所在地域，必须字段 */,
            Key: Key,
            FilePath: FilePath,
          },
          (err, data) => {
            uni.hideLoading();
            console.log(err || data);
            if (data) {
              resolve({
                statusCode: data.statusCode || 10000,
                url: ENV.cos_domain + Key,
              });
            } else {
              uni.showToast({
                title: "上传失败",
                icon: "none",
                mask: true,
              });
              resolve({ err: err ? err : "" });
            }
          }
        );
      })
      .catch((err) => {
        reject(err);
      });
  });
};
export default upload;